package cn.lqz.bucttrain.utils;


import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.lqz.bucttrain.enums.ResponseCodeEnum;
import cn.lqz.bucttrain.exceptions.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 数据库备份
 * @author ccit
 *
 */
@Slf4j
@Component
public class DataBaseUtils {
    /**
     * host
     */
    @Value("${service.database.host}")
    private String host;
    /**
     * port
     */
    @Value("${service.database.port}")
    private Integer port;

    /**
     * 用户名
     */
    @Value("${service.database.username}")
    private String userName;

    /**
     * 密码
     */
    @Value("${service.database.password}")
    private String password;

    /**
     * 数据库名字
     */
    @Value("${service.database.dbName}")
    private String dbName;

    /**
     * 备份路径
     */
    private static String backPath = "D:\\";
//	private static String backPath = "/home/";

    /**
     * 恢复路径
     */
    private static String filePath = "D:\\back.sql";
//	private static String filePath = "/home/back.sql";



    /**
     * 备份数据库db
     */
    public Boolean dbBackUp(String folderPath) throws Exception {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd-HH-mm-sss");
        String fileName = dateFormat.format(date) + ".sql";
        String pathSql = "";
        //输出流文件
        File fileSql;
        try {
            //判断系统
            /*String osName = System.getProperties().getProperty("os.name");
            if (osName.equals("Linux")) {
                pathSql = LbackPath + fileName;
            } else {
                pathSql = WbackPath + fileName;
            }*/

            pathSql = folderPath + File.separator + fileName;

            //输出流文件
            fileSql = new File(pathSql);
            //创建备份sql文件
            if (!fileSql.exists()) {
                fileSql.createNewFile();
            }

            //mysqldump -hlocalhost -uroot -p123456 db > /home/back.sql  整个库进行备份sql文件
            //mysqldump -hlocalhost -uroot -p123456 数据库名  数据表名 > /home/back.sql  单张表备份sql文件
            StringBuffer sb = new StringBuffer();
            sb.append("mysqldump");
            sb.append(" -h" + host);
            sb.append(" -u" + userName);
            sb.append(" -p" + password);
            sb.append(" " + dbName + " ");
            sb.append("-r");//java中必须使用"-r"替代">"
            sb.append(pathSql);

            Process process;
            //判断系统
            /*if (osName.equals("Linux")) {
                BufferedReader bufferedReader = null;
                PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(fileSql), "utf8"));
                process = Runtime.getRuntime().exec(" mysqldump -h" + ip + " -u" + root + " -p" + pwd + " --set-charset=UTF8 " + dbName + " -r /home/back.sql");
                InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
                bufferedReader = new BufferedReader(inputStreamReader);
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    printWriter.println(line);
                }
                printWriter.flush();
                log.info("-==[ 备份结束！ ]==-");
            } else {
                System.out.println("cmd命令为：" + "cmd /c " + sb.toString());
                process = Runtime.getRuntime().exec("cmd /c " + sb.toString());//执行语句
            }*/
            System.out.println("cmd命令为：" + "cmd /c " + sb);
            process = Runtime.getRuntime().exec("cmd /c " + sb);//执行语句
            process.waitFor();//等待上述命令执行完毕后打印下面log

            //输出错误信息
            InputStream is = process.getErrorStream();
            InputStreamReader isr = new InputStreamReader(is, "gbk");//读取
            System.out.println(isr.getEncoding());
            BufferedReader bufr = new BufferedReader(isr);//缓冲
            String line;
            while ((line = bufr.readLine()) != null) {
                System.out.println("error:" + line);
            }
            isr.close();
            Boolean success = process.exitValue() == 0 ;
            log.info("数据库备份结束，备份是否成功：{}",success );
            return success;
        } catch (Exception e) {
            throw e;
        }
    }


    /**
     * 备份数据库并返回文件对象
     * @return
     * @throws Exception
     */
    public File dbBackUpReturnFile(String folderPath) throws Exception {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd-HH-mm-sss");
        String fileName = dateFormat.format(date) + ".sql";
        String pathSql = "";
        //输出流文件
        File fileSql;
        try {
            //判断系统
            /*String osName = System.getProperties().getProperty("os.name");
            if (osName.equals("Linux")) {
                pathSql = LbackPath + fileName;
            } else {
                pathSql = WbackPath + fileName;
            }*/
            pathSql = folderPath + File.separator + fileName;
            //输出流文件
            fileSql = new File(pathSql);
            //创建备份sql文件
            if (!fileSql.exists()) {
                fileSql.createNewFile();
            }

            //mysqldump -hlocalhost -uroot -p123456 db > /home/back.sql  整个库进行备份sql文件
            //mysqldump -hlocalhost -uroot -p123456 数据库名  数据表名 > /home/back.sql  单张表备份sql文件
            StringBuffer sb = new StringBuffer();
            sb.append("mysqldump");
            sb.append(" -h" + host);
            sb.append(" -u" + userName);
            sb.append(" -p" + password);
            sb.append(" " + dbName + " ");
            sb.append("-r");//java中必须使用"-r"替代">"
            sb.append(pathSql);

            Process process;
            //判断系统
            /*if (osName.equals("Linux")) {
                BufferedReader bufferedReader = null;
                PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(fileSql), "utf8"));
                process = Runtime.getRuntime().exec(" mysqldump -h" + ip + " -u" + root + " -p" + pwd + " --set-charset=UTF8 " + dbName + " -r /home/back.sql");
                InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
                bufferedReader = new BufferedReader(inputStreamReader);
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    printWriter.println(line);
                }
                printWriter.flush();
                log.info("-==[ 备份结束！ ]==-");
            } else {
                System.out.println("cmd命令为：" + "cmd /c " + sb.toString());
                process = Runtime.getRuntime().exec("cmd /c " + sb.toString());//执行语句
            }*/
            System.out.println("cmd命令为：" + "cmd /c " + sb);
            process = Runtime.getRuntime().exec("cmd /c " + sb);//执行语句
            process.waitFor();//等待上述命令执行完毕后打印下面log

            //输出错误信息
            InputStream is = process.getErrorStream();
            InputStreamReader isr = new InputStreamReader(is, "gbk");//读取
            System.out.println(isr.getEncoding());
            BufferedReader bufr = new BufferedReader(isr);//缓冲
            String line;
            while ((line = bufr.readLine()) != null) {
                System.out.println("error:" + line);
            }
            isr.close();
            log.info("数据库备份结束，备份是否成功：{}",process.exitValue() == 0 );
            return fileSql;
        } catch (Exception e) {
            throw e;
        }
    }
}


